package com.pi.pro.xcmg.am.was.web.cust.controller;


import com.alibaba.fastjson.JSONArray;
import com.pi.common.CodesConstants;
import com.pi.framework.core.controller.BaseCrudController;
import com.pi.framework.core.service.ICrudService;
import com.pi.framework.core.util.DateUtils;
import com.pi.framework.core.util.SecurityUtils;
import com.pi.framework.core.util.StringUtils;
import com.pi.framework.core.util.csv.CsvExporter;
import com.pi.framework.web.util.CsvView;
import com.pi.pro.xcmg.am.common.XcmgAmConstants;
import com.pi.pro.xcmg.am.was.fac.service.WasCustomWorkService;
import com.pi.pro.xcmg.am.was.fac.service.WcsCustomWorkService;
import com.pi.wms.common.WmsConstants;
import com.pi.wms.dto.base.LocationLineDto;
import com.pi.wms.entity.TwaInventoryDetails;
import com.pi.wms.entity.TwaInventoryLotattr;
import com.pi.wms.entity.TwmBasMaterial;
import com.pi.wms.entity.TwtActAllocationList;
import com.pi.wms.fac.LocationResolver;
import com.pi.wms.service.AllocationService;
import com.pi.wms.service.InventoryLotattrService;
import com.pi.wms.service.LocationService;
import com.pi.wms.service.MaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.datatables.mapping.DataTablesInput;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


@Slf4j
@Controller
@RequestMapping("/outbound/picklist/ca")
public class CustApplyAllocationListController extends BaseCrudController<TwtActAllocationList, Long> {

	@Autowired
	protected AllocationService service;

	@Autowired
	private WasCustomWorkService customWorkService;

	@Autowired
	private MaterialService materialService;

	@Autowired
	private InventoryLotattrService lotattrService;

	@Autowired
	private LocationResolver locationResolver;

	@Autowired
	private WcsCustomWorkService wcsCustomWorkService;
	
	
	@Override
	protected ICrudService<TwtActAllocationList, Long> getCrudService() {
	    return service;
	}

	@Override
	protected String getPrefix() {
		return "allocation";
	}


    @PostMapping("shipline")
    public String shipLine(@RequestParam("ids") Long[] ids, Model model, HttpServletRequest request,
                           RedirectAttributes redirectAttributes) {

        model.addAttribute("params", getParams(request));
        if ((ids==null) || (ids.length==0)){
            addErrorMessage(redirectAttributes, "请选定分配数据进行确认.");
            return this.redirect("");
        }
        String m="";
        try{
            for (Long id:ids){
                if (id==null) {
                    continue;
                }
                m = this.customWorkService.shipmentByAllocationId(id, "", SecurityUtils.getLoginUsername());
                if (!StringUtils.isNullOrBlank(m)) {
                    addErrorMessage(redirectAttributes, "发运失败:找不到待发运作业.");
                    return this.redirect("");
                }
            }
        }catch (Exception e){
            m="发运发生异常.错误:"+e.getMessage();
            e.printStackTrace();
        }
        if(!StringUtils.isNullOrBlank(m)){
            addErrorMessage(redirectAttributes, "发运失败:"+m);
            return this.redirect("");
        }
        addSuccessMessage(redirectAttributes, "发运成功");
        return this.redirect("");
    }



    @PostMapping(value = { "/export" })
    public ModelAndView export(@RequestParam Map<String, Object> query, DataTablesInput input) {
        query.put("type", WmsConstants.TRANS_TYPE_SHIP);
        String inputParams = "";
        if (query.get("input")!=null){
            inputParams=query.get("input").toString();
        }
        if (StringUtils.isNotEmpty(inputParams)) {
            input = JSONArray.parseObject(inputParams, DataTablesInput.class);
        }
        input.setLength(-1);
        String ymd = DateUtils.format(new Date(), DateUtils.FORMAT_DATE_YYYY_MM_DD_HHMMSS);
        final DataTablesInput ins = input;
        Map<Long,TwmBasMaterial> materials=new HashMap<>();
        Map<Long,TwaInventoryLotattr> lotattrs=new HashMap<>();
        CsvExporter<TwtActAllocationList> exporter = new CsvExporter<TwtActAllocationList>() {
            @Override
            public String[] header() {
                return "单号,行号,物料编码,物料名称,数量,供应商,WBS,托盘码,源库位,目标库位,创建时间,创建人"
                        .split(",");
            }

            @Override
            public Collection<TwtActAllocationList> nextList(int pageSize, int page) {
                ins.setLength(pageSize);
                ins.setStart(page * pageSize);
                Pageable pageable = PageRequest.of(page, pageSize);
                Page<TwtActAllocationList> out = service.findAll(query,pageable);
                return out == null ? null : out.getContent();
            }

            @Override
            public Collection<String> toText(TwtActAllocationList d) {
                List<String> item = new ArrayList<String>();
                TwmBasMaterial mat=materials.get(d.getMaterialId());
                if (mat==null){
                    mat=materialService.lookup(d.getMaterialId());
                    if (mat!=null){
                        materials.put(mat.getId(), mat);
                    }
                }
                item.add(d.getDocNumber());
                item.add(d.getDocLinenumber());
                if (mat!=null){
                    item.add(mat.getCode());
                    item.add(mat.getName());
                }else{
                    item.add("");
                    item.add("");
                }
                item.add(d.getQty().stripTrailingZeros().toPlainString());
                TwaInventoryLotattr lotattr=lotattrs.get(d.getLotnoId());
                if (lotattr==null){
                    lotattr=lotattrService.lookup(d.getMaterialId());
                    if (lotattr!=null){
                        lotattrs.put(lotattr.getId(), lotattr);
                    }
                }
                if (lotattr!=null){
                    item.add(StringUtils.ifNullOrBlank(lotattr.getLotattr06(), CodesConstants.COMMON_WILDCARD));
                    item.add(StringUtils.ifNullOrBlank(lotattr.getLotattr07(), CodesConstants.COMMON_WILDCARD));
                }else{
                    item.add(CodesConstants.COMMON_WILDCARD);
                    item.add(CodesConstants.COMMON_WILDCARD);
                }
                item.add(d.getFromContainNumber());
                LocationLineDto loc=locationResolver.lookup(d.getFromLocId());
                if (loc!=null){
                    item.add(loc.getLocationCode());
                }else {
                    item.add("");
                }
                loc=locationResolver.lookup(d.getToLocId());
                if (loc!=null){
                    item.add(loc.getLocationCode());
                }else {
                    item.add("");
                }
                item.add(DateUtils.formatDateTime(d.getCreatedDate()));
                item.add(d.getCreatedBy());
                return item;
            }
        };
        return new ModelAndView(new CsvView(exporter, "allocation_list_" + ymd));
    }



    protected String redirect(String relativeUrl) {
		if(!com.pi.common.utils.StringUtils.isNullOrBlank(relativeUrl) && !relativeUrl.startsWith("/")) {
			relativeUrl = "/" + relativeUrl;
		}
		return "redirect:" + this.referUrl() + relativeUrl;
	}

	private String referUrl(){
		return "/outbound/picklist/";
	}

}
